# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Demonstrates using OAuth 2 and the Python Google APIs client library.

This is a command-line script that accesses Latitude API data.
"""

__author__ = "jeffy@google.com (Jeffrey Posnick)"

import httplib2
import os
import sys

from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run

class LatitudeOAuthDemo(object):
  """A class to interact with the Latitude API."""

  # CONSTANTS
  # The client id, and secret are copied from the Google APIs Console
  # <https://code.google.com/apis/console>
  CLIENT_ID = "393574119402.apps.googleusercontent.com"
  CLIENT_SECRET = "nErYHzU92Ye4AmI-SGNrzkN5"
  OAUTH_SCOPE = "https://www.googleapis.com/auth/latitude.current.best"

  def Authenticate(self):
    """Handles OAuth2 authentication.

    We rely on the OAuth2 support in the Google API client library.
    """
    # Use a file in the user's home directory as the credential cache.
    storage = Storage("%s/%s-oauth" % (os.path.expanduser("~"), sys.argv[0]))
    self.credentials = storage.get()
    if self.credentials is None or self.credentials.invalid:
      # If there are no valid cached credentials, take the user through the
      # OAuth2 login flow, and rely on the client library to cache the
      # credentials once that's complete.
      flow = OAuth2WebServerFlow(
        client_id=self.CLIENT_ID,
        client_secret=self.CLIENT_SECRET,
        scope=self.OAUTH_SCOPE,
        user_agent=sys.argv[0])
      self.credentials = run(flow, storage)

  def SetupHttpRequestObject(self):
    """Creates an httplib2 client and request headers for later use.

    The Google API client library takes care of associating the OAuth2
    credentials with a httplib2.Http object.
    """
    self.http = self.credentials.authorize(httplib2.Http())

  def GetCurrentLocation(self):
    """Calls the Latitude API to retrieve the current location.
    """
    service = build("latitude", "v1", http=self.http)
    return service.currentLocation().get().execute()


  def main(self):
    """Handles program execution."""
    self.Authenticate()
    self.SetupHttpRequestObject()
    current_location = self.GetCurrentLocation()
    print current_location


if __name__ == "__main__":
  latitude_oauth_demo = LatitudeOAuthDemo()
  latitude_oauth_demo.main()